package jeye.servlet.action;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class ActionFactory {
	
	private static final String ACTION_PARAMETER = "action";
	
	private static final Logger LOG = Logger.getLogger(ActionFactory.class);
	
	@Autowired
	@Qualifier("defaultAction")
	private ServletAction defaultAction;
	
	private Set<String> allowedActions = new HashSet<String>();

	public ServletAction createServletAction(HttpServletRequest request) {
		ApplicationContext appContext = getWebApplicationContext(request);
		String actionName = request.getParameter(ACTION_PARAMETER);
		
		if(!allowedActions.contains(actionName)) {
			LOG.info("Action \"" + actionName + "\" is forbidden. Redirecting do default action.");
		}
		else if(appContext.containsBean(actionName)) {
			return (ServletAction)appContext.getBean(actionName, ServletAction.class);
		}
		
		return defaultAction;
	}
	
	private ServletContext getServletContext(HttpServletRequest request) {
		return request.getSession().getServletContext();
	}
	
	private ApplicationContext getWebApplicationContext(HttpServletRequest request) {
		ServletContext servletContext = getServletContext(request);
		return WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
	}

	public void setAllowedActions(Set<String> allowedActions) {
		this.allowedActions = allowedActions;
	}
}
